package com.motong.gongdan.config.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.motong.gongdan.config.auth.LoginException;
import com.motong.gongdan.entity.*;
import com.motong.gongdan.service.*;
import com.motong.gongdan.util.StringUtil;
import com.motong.gongdan.vo.system.otherVo.WorkReportHandleVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Field;
import java.util.Objects;

/**
 * @author:fff
 * @time:2022/6/14
 */
@Component
public class CheckRulesInterceptor implements HandlerInterceptor {
    @Autowired
    MissionService missionService;
    @Autowired
    WorkOrderService workOrderService;
    @Autowired
    WorkReportService workReportService;
    @Autowired
    FormCheckRuleService formCheckRuleService;
    @Autowired
    DictService dictService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            FormCheckRules formCheckRules = handlerMethod.getMethodAnnotation(FormCheckRules.class);
            if (formCheckRules == null) {
                return true;
            }
            String body = "";
            if (StringUtils.equalsIgnoreCase(HttpMethod.POST.name(), request.getMethod())) {
                RequestWrapper requestWrapper = new RequestWrapper(request);
                body = requestWrapper.getBodyString(requestWrapper);
                WorkReportHandleVo vo = JSONObject.parseObject(body).toJavaObject(WorkReportHandleVo.class);
               this.checkRule(vo);
            } else {
                return true;
            }
        }
        return true;
    }

    public boolean checkRule(WorkReportHandleVo vo ) throws NoSuchFieldException, IllegalAccessException {
            if (vo != null) {
                WorkOrder wo = null;
                if (StringUtil.isNotBlank(vo.getWorkOrderCode())) {
                    wo = workOrderService.getOne(new QueryWrapper<WorkOrder>().eq("code", vo.getWorkOrderCode()));
                } else {
                    WorkReport workReport = workReportService.getById(vo.getId());
                    Mission mission = missionService.getById(workReport.getMissionId());
                    wo = workOrderService.getOne(new QueryWrapper<WorkOrder>().eq("code", mission.getWorkOrderCode()));
                }
                Mission mission = null;
                if (vo.getMissionId() == null) {
                    WorkReport workReport = workReportService.getById(vo.getId());
                    mission = missionService.getById(workReport.getMissionId());
                } else {
                    mission = missionService.getById(vo.getMissionId());
                }
                Mission before = null;
                if (mission.getLast() != 1 && mission.getLast() != 0) {
                    before = missionService.getOne(new QueryWrapper<Mission>().eq("work_order_code", mission.getWorkOrderCode()).eq("last", mission.getLast() - 1));
                } else if (mission.getLast() == 0) {
                    before = missionService.getOne(new QueryWrapper<Mission>().eq("work_order_code", mission.getWorkOrderCode()).eq("last", wo.getProcessId().split(",").length - 1));
                }
                if (mission.getProcessState() == 2 && Objects.isNull(vo.getId())) {
                    throw new LoginException("500", "工序已结束禁止报工");
                }
                String result = workReportService.checkRule(vo, mission, before);
                if (StringUtil.isNotBlank(result)) {
                    throw new LoginException("500", result);
                }
            }
            return true;
    }



    public String handleField(Object o, String valueS, String newRule, String s) throws NoSuchFieldException, IllegalAccessException {
        Field fields = o.getClass().getDeclaredField(valueS);
        fields.setAccessible(true);
        Integer num = Double.valueOf(fields.get(o).toString()).intValue();
        String newS = StringUtil.regReplace(s);
        return newRule.replaceAll(newS, num.toString());
    }

}
